//
//  YTLoginViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/4/28.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTLoginViewController.h"
#import "YTRegisterViewController.h"
#import "YTServiceAreaViewController.h"
#import "YTCountryCodeViewController.h"
#import "YTFindPasswordViewController.h"
#import "YTTabBarViewController.h"
#import "YTWebViewController.h"
#import "YTLoginViewModel.h"

@interface YTLoginViewController ()<YTCountryCodeDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNum;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UIButton *eyeButton;
@property (weak, nonatomic) IBOutlet UIButton *areaCode;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;

@property (strong, nonatomic) YTLoginViewModel *viewModel;

@end

@implementation YTLoginViewController

#pragma mark - lefcycle


#pragma mark - private

- (void)bindViewModel {
    RAC(_viewModel, areaCode) = RACObserve(_areaCode.titleLabel, text);
    RAC(_viewModel, isChecked) = RACObserve(_checkBtn, selected);
    RAC(_viewModel, phoneNum) = _phoneNum.rac_textSignal;
    RAC(_viewModel, password) = _password.rac_textSignal;
    _loginButton.rac_command = _viewModel.loginCommand;
    
    @weakify(self);
    // textField color
    UIColor *(^validateColor)(NSNumber *) = [NSObject yt_btnNormalColor:[UIColor blackColor] disabled:[UIColor redColor]];
    RAC(_phoneNum, textColor) = [[_viewModel.phoneVerify distinctUntilChanged] map:validateColor];
    RAC(_password, textColor) = [[_viewModel.passwordVerify distinctUntilChanged] map:validateColor];
    RAC(_loginButton, backgroundColor) = [[_viewModel.verifyAll distinctUntilChanged] map:^UIColor *(NSNumber *enabled) {
        return [enabled boolValue] ? kMainBlueColor : [UIColor lightGrayColor];
    }];
    
    [[self.eyeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *btn) {
        @strongify(self);
        btn.selected = !btn.selected;
        self.password.secureTextEntry = !btn.selected;
    }];
    
    [[self.checkBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *btn) {
        btn.selected = !btn.selected;
    }];
    
    // login btn
    [_viewModel.loginCommand.executing doNext:^(id x) {
        @strongify(self);
        [self.view endEditing:YES];
    }];
    
    [[_viewModel.loginCommand.executionSignals switchToLatest] subscribeNext:^(NSDictionary *response) {
        if ([response[@"resultCode"] integerValue] == 1000) {
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            if (_isModal) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            [UIApplication sharedApplication].keyWindow.rootViewController = [[YTTabBarViewController alloc] init];
        }
    }];
}

- (void)initialize {
    _viewModel = [[YTLoginViewModel alloc] init];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    @weakify(self);
    // navigation 
    [[self rac_signalForSelector:@selector(viewWillAppear:)] subscribeNext:^(id x) {
        @strongify(self);
        [self.navigationController setNavigationBarHidden:YES animated:x];
        [self yt_changStatusBarWithStyle:UIStatusBarStyleLightContent];
    }];
    
    YTRegisterViewController *registerVC = [[YTRegisterViewController alloc] init];
    registerVC.regsterSuccess = [RACSubject subject];
    [registerVC.regsterSuccess subscribeNext:^(RACTuple *userInfo) {
        @strongify(self);
        [self loadUserAccount:userInfo];
    }];
    
    [[_areaCode rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        YTCountryCodeViewController *countryCode = [[YTCountryCodeViewController alloc] init];
        countryCode.delegate = self;
        [self.navigationController pushViewController:countryCode animated:YES];
    }];
    
    /// 各类通知监听
    [[[NSNotificationCenter defaultCenter]
      rac_addObserverForName:YTUserRegisterSuccessNotification object:nil]
      subscribeNext:^(NSNotification *userInfo) {
         @strongify(self);
         [self loadUserAccount:(RACTuple *)userInfo.object];
     }];
    
    [[[NSNotificationCenter defaultCenter]
      rac_addObserverForName:YTUserNeedToLoginNotification object:nil]
      subscribeNext:^(id x) {
        @strongify(self);
        self.isModal = YES;
    }];
}

- (IBAction)agreementAction:(UIButton *)sender {
    YTWebViewController *web = [[YTWebViewController alloc] init];
    web.urlString = @"http://api.yitu8.cn/api/driver/v2.0/h5/agreement.htm";
    [self.navigationController pushViewController:web animated:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    @weakify(self);
    if ([segue.identifier isEqualToString:@"FindPassword"]) {
        YTFindPasswordViewController *findPassword = segue.destinationViewController;
        findPassword.resetSuccess = [RACSubject subject];
        [findPassword.resetSuccess subscribeNext:^(RACTuple *userInfo) {
            @strongify(self);
            [self loadUserAccount:userInfo];
        }];
    }
}

- (void)didSelectWithCountryCode:(NSString *)countryCode {
    [_areaCode setTitle:[NSString stringWithFormat:@"+ %@", countryCode] forState:UIControlStateNormal];
}

- (void)loadUserAccount:(RACTuple *)userInfo {
    self.phoneNum.text = userInfo.first;
    self.password.text = userInfo.last;
    self.phoneNum.textColor = [UIColor blackColor];
    self.password.textColor = [UIColor blackColor];
}

@end
